import { ref } from 'vue'
import { showNotify } from 'vant';
import 'vant/es/notify/style';
import { alipayPrepayInfo,  tenpayH5PrepayInfo } from '@/api/pay';
import { TenpayPrepayResult } from '@/api/model/payModel';

const formHtml = ref('');


export const alipay = (prepayInfo:any) => {
  // closeKeyboard();
  const div = document.createElement('div');
  div.innerHTML = prepayInfo // res.data是返回的表单
  document.body.appendChild(div);
  (document.forms as any).alipaysubmit.submit();
};
export const alipayH5 = (prepayInfo : any) => {
  alipayPrepayInfo(prepayInfo)
    .then((ret) => {
      // console.log('alipay prepay ret', ret);
      formHtml.value = ret.result.body;

      const div = document.createElement('div');
      div.innerHTML = prepayInfo; // res.data是返回的表单
      document.body.appendChild(div);
      (document.forms as any).alipaysubmit.submit();
    })
    .catch((e) => {
      const msg = e.message ?? e.msg;
      showNotify({ type: 'danger', message: msg });
    });
};

const tenpayPrepayData = ref({
  appId: '',
  timeStamp: '',
  nonceStr: '',
  package: '',
  signType: '',
  paySign: '',
});
export const tenpay = (prepayInfo:any) => {
  //closeKeyboard();
  if ((window as any).WeixinJSBridge === 'undefined') {
    if (document.addEventListener) {
      (document as any).addEventListener('WeixinJSBridgeReady', onBridgeReady(tenpayPrepayData.value), false);
    } else if ((document as any).attachEvent) {
      (document as any).attachEvent('WeixinJSBridgeReady', onBridgeReady(tenpayPrepayData.value));
      (document as any).attachEvent('OnWeixinJSBridgeReady', onBridgeReady(tenpayPrepayData.value));
    }
  } else {
    onBridgeReady(prepayInfo);
  }

};
export const tenpayH5 = (prepayInfo : any) => {
  // 微信H5支付 https://pay.weixin.qq.com/wiki/doc/api/wxpay/ch/pay/OfficialPayMent/chapter5_5.shtml
  tenpayH5PrepayInfo({
    scene: 5,
    appId: prepayInfo.appId,
    orderNo: prepayInfo.orderNo,
    orderName: prepayInfo.orderName,
    payAmount: prepayInfo.payAmount,
    attach: prepayInfo.attach,
  })
    .then((ret) => {
      if (ret.h5_url) {
        window.open(ret.h5_url);
      } else {
        showErrMsg(ret);
      }
    })
    .catch((e) => {
      showErrMsg(e);
    });
};
const onBridgeReady = (requestData : TenpayPrepayResult) => {
  (window as any).WeixinJSBridge.invoke('getBrandWCPayRequest', requestData, (res : any) => {
    if (res.err_msg === 'get_brand_wcpay_request:ok') {
      showNotify({ type: 'success', message: '支付成功' });
      // 跳转到支付成功页
    } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
      showNotify({ type: 'warning', message: '支付取消' });
    } else if (res.err_msg === 'get_brand_wcpay_request:fail') {
      showNotify({ type: 'danger', message: '支付失败' });
    }
  });
};


const showErrMsg = (e : any) => {
  const msg = e.message ?? e.msg;
  showNotify({ type: 'warning', message: msg });
};
